"""知识点创建相关视图

此模块包含用于创建知识点的视图函数和相关功能。
"""
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from core.models import Chapter, KnowledgePoint, TeacherSubjectAssignment
from core.forms.knowledge_point_form import KnowledgePointForm
from core.utils import log_operation


def _has_subject_permission(request: HttpRequest, subject_id: int) -> bool:
    """检查用户是否有权限操作指定学科

    Args:
        request: HTTP请求对象
        subject_id: 学科ID

    Returns:
        bool: 用户是否有权限
    """
    return TeacherSubjectAssignment.objects.filter(
        teacher=request.user,
        subject_id=subject_id
    ).exists()


@login_required
def knowledge_point_create(request: HttpRequest) -> HttpResponse:
    """创建新知识点

    该视图函数处理知识点的创建操作，包括显示表单和处理表单提交。
    验证用户是否有权限操作指定章节所属的学科，并记录操作日志。

    Args:
        request: HTTP请求对象，包含章节ID参数

    Returns:
        HttpResponse: 渲染的创建表单页面或重定向到知识点列表
    """
    chapter_id = request.GET.get('chapter_id')

    if not chapter_id:
        messages.error(request, '章节ID不能为空')
        return redirect('core:index')

    chapter = get_object_or_404(Chapter, id=chapter_id)

    # 验证用户是否有权限操作此章节所属的学科
    if not _has_subject_permission(request, chapter.subject_id):
        return render(request, 'knowledge_point/permission_denied.html', status=403)

    if request.method == 'POST':
        form = KnowledgePointForm(request.POST)
        if form.is_valid():
            with transaction.atomic():
                knowledge_point = form.save(commit=False)
                knowledge_point.chapter = chapter
                knowledge_point.save()

            log_operation(
                user=request.user,
                operation_type='create',
                content_type='KnowledgePoint',
                object_id=knowledge_point.id,
                object_name=knowledge_point.name,
                request=request,
                details=f'创建知识点: {knowledge_point.name}'
            )

            messages.success(request, '知识点创建成功')
            return redirect('core:knowledge_point_list', chapter_id=chapter.id)
    else:
        form = KnowledgePointForm()

    return render(request, 'knowledge_point/knowledge_point_form.html', {
        'form': form,
        'chapter': chapter,
        'title': '创建知识点'
    })